<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            border: 10px solid #000;
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>

<body>

    <div></div>

    <script>

        // 鼠标中心跟随
        //   鼠标的位置减去盒子自身宽高的一半

        var oDiv = document.querySelector('div') ;

        var r = oDiv.offsetWidth / 2 ;
        var maxX = document.documentElement.clientWidth - oDiv.offsetWidth ;
        var maxY = document.documentElement.clientHeight - oDiv.offsetHeight ;

        document.onmousemove = function(e) {
            var x = e.x - r ;
            var y = e.y - r ;
            if(x < 0) x = 0 ;
            if(y < 0) y = 0 ;
            if(x > maxX) x = maxX ;
            if(y > maxY) y = maxY ;
            oDiv.style.left = x + 'px' ;
            oDiv.style.top = y + 'px' ;
        }

    </script>

</body>

</html>